package com.zzzptc.lzh.bookreader;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zzzptc.lzh.bookreader.Bean.Book;
import com.zzzptc.lzh.bookreader.Bean.User;

import org.litepal.LitePal;

public class LoginActivity extends AppCompatActivity {
    private EditText usnedit,psdedit;
    private Button loginbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getUser();
        getBook();
        initView();
        setListener();
    }

    private void getBook() {
        new Book(0,"全球旧日","来份松果",R.mipmap.quanqiu).save();
        new Book(0,"在离死亡最近的地方","一粒灰烬",R.mipmap.siwang).save();
        new Book(0,"噩梦将袭","佛系面包",R.mipmap.emeng).save();
        new Book(0,"我行走在诸天世界","郭家",R.mipmap.woxingzou).save();
        new Book(0,"深渊之夏","云华山人",R.mipmap.shenyuan).save();
    }

    private void getUser() {
        new User(0,"张三","123").save();
        new User(0,"李四","456").save();
        new User(0,"王五","789").save();
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usnedit.getText().toString().trim();//用两个String型接住输入框的内容
                String psd=psdedit.getText().toString().trim();
                User u=confirmUser(usn,psd);
                if (u==null){
                    //登录失败
                    Toast.makeText(LoginActivity.this, "请输入正确的用户名和密码", Toast.LENGTH_SHORT).show();
                }else{
                    Intent it=new Intent(LoginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("userid",u.getId());
                    editor.putString("username",u.getUsername());
                    editor.apply();
                    startActivity(it);
                }
            }
        });
    }

    private User confirmUser(String usn, String psd) {
        for (User u: LitePal.findAll(User.class)){
            if (u.getUsername().equals(usn)&&u.getPassword().equals(psd)){
                return u;
            }
        }
        return null;
    }

    private void initView() {
        usnedit=findViewById(R.id.usnedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);
    }
}
